Ext.onReady(function() {
	Ext.QuickTips.init(); //为组件提供提示信息功能，form的主要提示信息就是客户端验证的错误信息。
	Ext.form.Field.prototype.msgTarget='side'; //提示的方式，枚举值为: 
	//mortgageId,后台传入...
	/**
	 * 应收款信息
	 */
	var mortgageInfo = Ext.create("Ext.form.Panel", {
		labelAlign: "right",
        items:{
            border: false,
            items:[{
		 		xtype: "fieldset",title: "<font color='blue'>应收款信息</font>", layout: "form",
		 		items: [
		 			{
		 				xtype: "fieldcontainer", layout: "column",
						items:[
							{xtype: "displayfield",name: "roomName",fieldLabel: "房号", width: 450},
							{xtype: "displayfield",name: "customerName",fieldLabel: "客户名称",width: 300}
						]
					},
					{
		 				xtype: "fieldcontainer", layout: "column",
						items:[
							{xtype: "displayfield",name: "paymentMethod",fieldLabel: "付款方式", width: 450},
							{xtype: "displayfield",name: "signedDate",fieldLabel: "签约日期", width: 300,
								renderer : function(val) {
									if(val!=null&&val!=""){
										return Ext.Date.format(new Date(val), "Y-m-d");
									}
									return null;
								}
							}
						]
					},
					{
		 				xtype: "fieldcontainer", layout: "column",
						items:[
							{xtype: "displayfield",name: "signAmount",fieldLabel: "合同金额", width: 450, renderer: Ext.util.Format.numberRenderer('0,000.00')},
							{xtype: "displayfield",name: "hrrReceived",fieldLabel: "合同已收金额", width: 300, renderer: Ext.util.Format.numberRenderer('0,000.00')}
						]
					},
					{
		 				xtype: "fieldcontainer", layout: "column",
						items:[
							{xtype: "displayfield",name: "receivablesFunds",fieldLabel: "款项类型", width: 450},
							{xtype: "displayfield",name: "mortgageAmount",fieldLabel: "按揭金额", width: 300, renderer: Ext.util.Format.numberRenderer('0,000.00')}
						]
					},
					{
		 				xtype: "fieldcontainer", layout: "column",
						items:[
							{xtype: "displayfield",name: "expectLoadDate",fieldLabel: "放款日期", width: 450,
								renderer : function(val) {
									if(val!=null&&val!=""){
										return Ext.Date.format(new Date(val), "Y-m-d");
									}
									return null;
								}
							},
							{xtype: "displayfield",name: "currReceivedAmount",fieldLabel: "已放款金额", width: 300, renderer: Ext.util.Format.numberRenderer('0,000.00')}
						]
					},
					{
		 				xtype: "fieldcontainer", layout: "column",
						items:[
							{xtype: "displayfield",name: "updateTime",fieldLabel: "处理日期", width: 450,
								renderer : function(val) {
									if(val!=null&&val!=""){
										return Ext.Date.format(new Date(val), "Y-m-d H:i:s");
									}
									return null;
								}
							},
							{xtype: "displayfield",name: "operationUser",fieldLabel: "处理人", width: 300}
						]
					}
				]}
			]
        }
	});
	
	//上传图片展示框
	var showImgPanel = Ext.create('Ext.Panel', {
        width:600,
       	height:120,
        frame: true,
        collapsible: false,
      	autoScroll:true,
      	bodyStyle: 'overflow-y:hidden; overflow-x:auto',
        layout: "hbox"
    });
	
	//加载认购信息
    mortgageInfo.getForm().load({
	    url: jypath + "/deal/mortgage/getMortgageRecordById",
	    params: {"id": mortgageId},
	    success: function(form, action){
	    	var fileList = action.result.data.fileList;
	    	if(fileList){
    			for(var ii=0; ii<fileList.length; ii++){
    				var httpUrl = fileList[ii];
	    			var imgs="<a href='"+httpUrl+"' target='_blank'><img style='width: 80px; height: 90px;' title='' src='"+httpUrl+"'/></a>";
		        	var imgPanel = Ext.create("Ext.Panel", {
				        html: imgs
		        	})
					showImgPanel.add(imgPanel);
    			}
				Ext.getCmp("certification").show();
	    	}
			
			if(action.result.data.ProcessStatus == 0){
				Ext.get("btn_changeRecord").hide();
			}else if(action.result.data.ProcessStatus == 1){
				Ext.get("btn_changeRecord").show();
			}
    	},
	    failure: function(form, action) {
	    	Ext.get("btn_save").hide();
	    	Ext.get("btn_changeRecord").hide();
	        Ext.Msg.alert("加载失败", action.result.errorMessage);
	    }
	});
	/**
	 * 按揭处理信息
	 */
	var progressLoanList = [
         {"value":"0","text":"未办理"},
         {"value":"1","text":"未达办理条件"},
         {"value":"2","text":"资料/手续齐全"},
         {"value":"3","text":"抵押办理中"},
         {"value":"4","text":"贷款审批中"},
         {"value":"5","text":"复审需补材料"},
         {"value":"6","text":"待放款(无额度)"},
         {"value":"7","text":"待放款(有额度)"},
         {"value":"8","text":"已放款"}
     ];
	var progressLoanStore = Ext.data.Store({
    	autoDestroy: true,
        fields :["value","text"],
        data : progressLoanList
    });
    
    var bankStore = Ext.data.Store({
    	fields: ["id","dictionaryName"],
        remoteSort: false,
        proxy: {
            type: 'ajax',
            url: jypath+'/estate/dictionary/getDictionary',
            extraParams: {"dictionaryType": "BK"},
            actionMethods: {read: 'POST'},
            reader: {
                type: 'json',
                root: 'rows'
            }
        },
        autoLoad: true  //即时加载数据
    });
	
    //按揭附件表单
	var ajaxFileUploadForm = Ext.create("Ext.form.Panel", {
		border: false,
		items: [{
            xtype: 'filefield',
            fieldLabel: "上传附件",
            buttonText: "上传附件",
            name: "file",
            layout: "hbox",
            validator: function(value){
            	if(value){
            		if(!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG|BMP)$/.test(value)){
			      		return "图片格式不正确!";
				    }else{
				    	return true;
				    }
            	}else{
			    	return true;
			    }
			},
            listeners: {
        		change: function(file){
        			var form = ajaxFileUploadForm.getForm();
	                if(form.isValid()){
		                form.submit({
		                    url: jypath + '/common/file/extUploadFile?type=1',
		                    waitMsg: '附件上传中,请稍候...',
		                    success: function(form, action) {
		                    	var fileName = action.result.fileName;
		                    	var httpUrl = action.result.url;
		                    	var imgs="<a href='"+httpUrl+"' target='_blank'><img style='width: 80px; height: 90px;' title='"+fileName+"' src='"+httpUrl+"'/></a>";
		                    	var imgPanel = Ext.create("Ext.Panel", {
							        html: imgs
		                    	})
								showImgPanel.add(imgPanel);
								//添加隐藏字符串
								var fileArr = processInfo.getForm().findField("fileArr").getValue();
								if(!fileArr){
									fileArr = httpUrl;
								}else{
									fileArr = fileArr + "|" + httpUrl;
								}
								processInfo.getForm().findField("fileArr").setValue(fileArr);
								Ext.getCmp("certification").show();
			       			},
			       			failure: function(form, action){
	                        	Ext.Msg.alert('Failure', 'Your photo "' + action.result.fileName + '" has been uploaded.');
			       			}
		                });
	                }
        		}
        	}
        },{
        	xtype: "fieldcontainer",
        	layout: "hbox",
        	fieldLabel: "按揭附件",
        	id: "certification",
        	name: "certification",
        	hidden: true,
        	items: [showImgPanel]
        }]
	});
    
	var processInfo = Ext.create("Ext.form.FormPanel", {
        bodyPadding:5,
        border: false,
        fieldDefaults: {
            labelWidth: 120,
            labelAlign: "right"
        },
        items: [
        	{
        		xtype: "fieldset",title: "<font color='blue'>按揭处理信息</font>", layout: "form",
        		items:[
        			{xtype: "textfield", name: "id", fieldLabel: "主键Id", hidden: true, value: mortgageId},
		        	{
	                	xtype : 'textfield', fieldLabel : '按揭凭证',
				    	name: "fileArr", readOnly: true, hidden: true
	                },
	        		{
		        		xtype: "radiogroup", fieldLabel: "客户自行办理按揭", width: 255, layout: "hbox",
		        		items: [
							{boxLabel: '是&emsp;&emsp;', name: 'customerSelf', inputValue: '1', id: 'self'},
		    				{boxLabel: '否', name: 'customerSelf', inputValue: '0', id: 'other', checked: true}
						]
        			},
	        		{
		        		xtype: "fieldcontainer", layout: "column",
		        		items: [
		        			{
				        		xtype: "radiogroup", fieldLabel: "资料是否齐全 ", width: 235,
				        		items: [
				    				{boxLabel: '是', name: 'completeStatus', inputValue: '0', id: 'yes', checked: true},
									{boxLabel: '否', name: 'completeStatus', inputValue: '1', id: 'no'}
								]
		        			},
	        				{xtype: "datefield", name: "ext_completeDate", width: 235, fieldLabel: "齐全日期", format: "Y-m-d"}
	        			]
		        	},
		        	{
		        		xtype: "fieldcontainer", layout: "hbox",
	    				items:[
		    				{
			    				xtype : 'combobox',
								fieldLabel : '贷款审批进度',
								store: progressLoanStore,
						    	displayField: "text",
						    	valueField: "value",
						    	id: "progressLoan",
						    	name: "progressLoan",
						    	editable: false, width: 235,
						    	allowBlank: false,
				                blankText:'不能为空'
		    				},
		    				{xtype: "datefield", name: "ext_expectLoadDate", width: 235, fieldLabel: "预计放贷时间", format: "Y-m-d", allowBlank: false,
				                blankText:'不能为空'}
	    				]
    				},
    				{
		        		xtype: "fieldcontainer", layout: "hbox",
	    				items:[
		    				{
								xtype : 'combobox',
								fieldLabel : '贷款银行',
								store: bankStore,
						    	displayField: "dictionaryName",
						    	valueField: "id",
						    	id: "bankId",
						    	name: "bankId",
						    	editable: false,
						    	allowBlank: false, width: 235,
				                blankText:'不能为空'
						    },
		    				{xtype: "textfield", name: "bankDetailName", width: 235, fieldLabel: "银行具体名称", maxLength: 100}
	    				]
    				},
    				{
		        		xtype: "fieldcontainer",
	    				items:[
		    				{xtype: "textareafield", name: "remark", fieldLabel: "情况说明", maxLength: 999, width: 472, heignt: 300}
	    				]
    				},
					{
		        		xtype: "fieldcontainer",
			            layout: "hbox",
			            items: [{
			        		xtype: "fieldcontainer",
				            layout: "hbox",
				            items: [ajaxFileUploadForm]
			        	}]
		        	}
        		]
        	}
        ]
	});
	
	//加载认购信息
    processInfo.getForm().load({
	    url: jypath + "/deal/mortgage/getMortgageRecordById",
	    params: {"id": mortgageId},
	    success: function(form, action){
	    	var completeDate = Ext.util.Format.date(action.result.data.completeDate, 'Y-m-d' );
	    	var expectLoadDate =Ext.util.Format.date(action.result.data.expectLoadDate, 'Y-m-d' );
	    	processInfo.getForm().findField("ext_completeDate").setValue(completeDate);
	    	processInfo.getForm().findField("ext_expectLoadDate").setValue(expectLoadDate);
    	},
	    failure: function(form, action) {
	    	Ext.get("btn_save").hide();
	    	Ext.get("btn_changeRecord").hide();
	        Ext.Msg.alert("加载失败", action.result.errorMessage);
	    }
	});
	
	var changeRecordStore = Ext.create('Ext.data.Store', {
		//最后字段userCode,实际为userName.
	    fields: ["oldProgressLoan","nowProgressLoan", "remark", "createTime", "userCode"],
        pageSize: 10,  //页容量5条数据
        //是否在服务端排序 （true的话，在客户端就不能排序）
        remoteSort: false,
        proxy: {
            type: 'ajax',
            url: jypath+'/deal/mortgage/mortgageFollowList',
            extraParams: {"mortgageRecordId": mortgageId},
            //默认参数,必填.
            actionMethods: { read: 'POST' },
            reader: {
            	//这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
                type: 'json', //返回数据类型为json格式
                root: 'rows',  //数据
                totalProperty: 'total' //数据总条数
            }
        },
        autoLoad: true  //即时加载数据
	});
	
	var changeRecords = Ext.create('Ext.grid.Panel', {
		width: 500,
		height: 400,
	    store: changeRecordStore,
	    columns: [
	        {text: '原贷款审批进度',  dataIndex: 'oldProgressLoan'},
	        {text: '现贷款审批进度', dataIndex: 'nowProgressLoan'},
	        {text: '说明', dataIndex: 'remark'},
	        {text: '操作时间', dataIndex: 'createTime', width: 150,
	        	renderer : function(val) {
					if(val!=null&&val!=""){
						return Ext.Date.format(new Date(val), "Y-m-d H:i:s");
					}
					return null;
				}
	        },
	        {text: '操作人', dataIndex: 'userCode'}
	    ],
	    dockedItems: [{
            xtype: 'pagingtoolbar',
            store: changeRecordStore,
            dock: 'bottom',
            emptyMsg: '没有数据',
            displayInfo: true,
            displayMsg: '当前显示{0}-{1}条记录 / 共{2}条记录 ',
            beforePageText: '第',
            afterPageText: '页/共{0}页'
        }]
	});
	
	var mortgageDetail = Ext.create("Ext.form.Panel", {
		items: [mortgageInfo, processInfo],
		tbar : [
			{
				xtype: "button",
				text : "返回",
				id: "btn_back",
				name: "btn_back",
				icon : jypath + '/resources/ExtJSicons/shape_move_backwards.png',
				listeners: {
					click: function(){
						history.go(-1);
					}
				}
			},{
				xtype: "button",
				text : "保存",
				id: "btn_save",
				name: "btn_save",
				icon : jypath + '/resources/ExtJSicons/database_add.png',
				listeners:{
					click: function(){
						var form = processInfo.getForm();
					    if(form.isValid()){
					    	// 发送请求
					    	var waiting = Ext.Msg.wait('正在处理，请稍等...','','');
							Ext.Ajax.request({
								method: "POST",
								url: jypath + "/deal/mortgage/addMortgageFollow",
								params: processInfo.getValues(),
								success: function(response, options){
									if(waiting != null){
										waiting.hide();
									}
									var jsonResult = Ext.decode(response.responseText);
									if(jsonResult.success==true){
										Ext.Msg.alert('成功', "操作成功");
										location.href = jypath + "/deal/mortgage/index";
									}else{
										Ext.Msg.alert('错误', jsonResult.errorMessage);
									}
								},
								failure: function(response, options){
									Ext.Msg.alert('错误', '请求超时.');
								}
							});
						}
					}
				}
			},
			{
				xtype: "button",
				text : "变更记录",
				id: "btn_changeRecord",
				name: "btn_changeRecord",
				hidden:changeType,
				icon : jypath + '/resources/ExtJSicons/book_open.png',
				listeners:{
					click: function(){
						Ext.create('Ext.window.Window', {
						    title: '按揭变更记录',
						    height: 300,
						    layout: 'fit',
						    items: [changeRecords],
						    closeAction: "hide"
						}).show();
					}
				}
			}
		],
		renderTo: Ext.getBody()
	});
	
});